package com.meida.module.system.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.meida.common.enums.AuthStatusEnum;
import com.meida.common.enums.YesNoEnum;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.GetModel;
import com.meida.common.mybatis.model.PageModel;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.model.UpdateModel;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.system.client.entity.SysArea;
import com.meida.module.system.client.entity.SysCompany;
import com.meida.module.system.provider.mapper.SysCompanyMapper;
import com.meida.module.system.provider.service.SysAreaService;
import com.meida.module.system.provider.service.SysCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 企业表 服务实现类
 *
 * @author flyme
 * @date 2019-06-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysCompanyServiceImpl extends BaseServiceImpl<SysCompanyMapper, SysCompany> implements SysCompanyService {
    @Autowired
    private SysAreaService areaService;


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody<EntityMap> get(GetModel model) {
        CriteriaQuery cq = new CriteriaQuery(model, SysCompany.class);
        cq.select(SysCompany.class, "companyId", "companyName", "companyLogo", "companyDesc", "designState", "proId", "cityId", "areaId", "auditState", "businessLic", "companyAddress", "businessLicNo", "areaName", "businessScope", "auditContent", "linkMan", "linkTel");
        setCollecon(cq);
        cq.eq("companyId", model.getId());
        return baseGet(cq);
    }


    @Override
    public ResultBody identification(CriteriaUpdate<SysCompany> cu) {
        cu.put("auditState", AuthStatusEnum.AUTHING.getCode());
        SysCompany company = cu.getEntity(SysCompany.class);
        Long areaId = company.getAreaId();
        Long proId = company.getProId();
        Long cityId = company.getCityId();

        Long userId = OpenHelper.getUserId();
        String areaName = "";
        if (FlymeUtils.isNotEmpty(proId)) {
            SysArea pro = areaService.getById(proId);
            areaName += pro.getAreaName();
        }
        if (FlymeUtils.isNotEmpty(cityId)) {
            SysArea city = areaService.getById(cityId);
            areaName += city.getAreaName();
        }
        if (FlymeUtils.isNotEmpty(areaId)) {
            SysArea area = areaService.getById(areaId);
            areaName += area.getAreaName();
        }
        cu.put("managerId", userId);
        cu.put("areaName", areaName);
        ResultBody resultBody = baseEdit(cu);
        if (resultBody.isOk()) {
            resultBody.setMsg("申请成功");
        }
        return resultBody;
    }


    @Override
    public ResultBody setAuditState(Map map) {
        CriteriaUpdate<SysCompany> cq = new CriteriaUpdate(map, entityClass);
        SysCompany company = cq.getEntity(SysCompany.class);
        Long companyId = company.getCompanyId();
        ApiAssert.isNotEmpty("主键不能为空", companyId);
        Integer auditState = company.getAuditState();
        cq.set("auditState", auditState);
        cq.set("auditContent", company.getAuditContent());
        ResultBody resultBody = baseUpdate(cq);
        if (resultBody.isOk()) {
            return ResultBody.ok("审核成功", auditState);
        } else {
            return ResultBody.failed("审核失败");
        }
    }

    @Override
    public ResultBody resetAuditState(Long companyId) {
        ApiAssert.isNotEmpty("主键不能为空", companyId);
        UpdateWrapper product = new UpdateWrapper();
        product.set("auditState", AuthStatusEnum.NOAUTH.getCode());
        product.set("auditContent", "");
        product.in("companyId", companyId);
        boolean result = update(product);
        return ResultBody.ok("", 0);

    }

    @Override
    public Boolean checkByCompanyName(String companyName, String businessLicNo) {
        QueryWrapper<SysCompany> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(SysCompany::getCompanyName, companyName).or().eq(FlymeUtils.isNotEmpty(businessLicNo), SysCompany::getBusinessLicNo, businessLicNo);
        int count = count(queryWrapper);
        return count > 0 ? true : false;
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<EntityMap> listRecommend(CriteriaQuery cq, int count, boolean collecon, String companyType) {
        cq.select(SysCompany.class, "companyId", "companyName", "companyLogo");
        if (collecon) {
            setCollecon(cq);
        }
        cq.eq("auditState", AuthStatusEnum.AUTHSUCCESS.getCode());
        cq.eq("company.recommend", YesNoEnum.YES);
        cq.eq("companyType", companyType);
        cq.orderByDesc("company.createTime");
        cq.last("limit " + count);
        return selectEntityMap(cq);
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody<EntityMap> pageList(PageModel model) {
        CriteriaQuery cq = new CriteriaQuery(model, SysCompany.class);
        cq.select(SysCompany.class, "companyId", "companyName", "companyLogo", "areaName", "companyType", "designState", "accountName", "companyAddress", "linkMan", "linkTel", "recommend", "auditState", "businessLicNo", "businessLic");
        setCollecon(cq);
        cq.likeByField(SysCompany.class, "companyName");
        cq.eq(SysCompany.class, "companyType");
        cq.eq(SysCompany.class, "accountName");
        cq.eq(SysCompany.class, "auditState");
        return basePageList(cq);
    }


    private void setCollecon(CriteriaQuery<EntityMap> cq) {
        //是否添加收藏标记
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isNotEmpty(userId)) {
            cq.addSelect("(select count(targetId) from sys_collecon sc where sc.targetId=company.companyId and targetEntity='SysCompany' and userId=" + userId + ") colleconTag");
        }
    }

    @Override
    public Boolean updateVisitCount(Long companyId, Integer num) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "visitCount=visitCount+" + num);
        cu.ge("visitCount", 0);
        cu.eq(true, "companyId", companyId);
        return update(cu);
    }

    @Override
    public ResultBody updateLookCount(Long companyId, Integer num) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "lookCount=lookCount+" + num);
        cu.ge("lookCount", 0);
        cu.eq(true, "companyId", companyId);
        Boolean up = update(cu);
        return ResultBody.ok();
    }

    @Override
    public ResultBody edit(UpdateModel model) {
        CriteriaUpdate<SysCompany> cu = new CriteriaUpdate(model, SysCompany.class);
        SysCompany company = cu.getEntity(SysCompany.class);
        Long areaId = company.getAreaId();
        Long proId = company.getProId();
        Long cityId = company.getCityId();
        String areaName = "";
        if (FlymeUtils.isNotEmpty(proId)) {
            SysArea pro = areaService.getById(proId);
            areaName += pro.getAreaName();
        }
        if (FlymeUtils.isNotEmpty(cityId)) {
            SysArea city = areaService.getById(cityId);
            areaName += city.getAreaName();
        }
        if (FlymeUtils.isNotEmpty(areaId)) {
            SysArea area = areaService.getById(areaId);
            areaName += area.getAreaName();
        }
        cu.put("areaName", areaName);
        return baseEdit(cu);
    }

    @Override
    public ResultBody setRecommend(Long[] ids, Integer recommend) {
        ApiAssert.isNotEmpty("主键不能为空", ids);
        UpdateWrapper product = new UpdateWrapper();
        product.set("recommend", recommend);
        product.in("companyId", ids);
        boolean result = update(product);
        return ResultBody.result(result, recommend);
    }

    @Override
    public SysCompany getManagerId(Long managerId) {
        CriteriaQuery cq = new CriteriaQuery(SysCompany.class);
        cq.eq(true, "managerId", managerId);
        return getOne(cq);
    }

    @Override
    public int totalCount(Map map, Integer auditState) {
        CriteriaQuery cq = new CriteriaQuery(SysCompany.class);
        if (auditState.equals(0)) {
            cq.ne("auditState", 2);
        } else {
            cq.eq("auditState", 2);
        }
        return count(cq);
    }

}
